define([
    'require',
], function (require) {
    require(['ionic']
        , function () {
            angular.module('myApp', ['ionic'])
                .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
                    $stateProvider
                        .state('home', {
                            url: '/home',
                            templateUrl: 'templates/home.html',
                            controller: 'HomeCtrl'
                        })
                        .state('sign', {
                            url: '/sign',
                            templateUrl: 'templates/sign.html',
                            controller: 'SignCtrl'
                        })
                        .state('report', {
                            url: '/report',
                            templateUrl: 'templates/report.html',
                            controller: 'ReportCtrl'
                        });
                    $urlRouterProvider.otherwise('/home');

                    $ionicConfigProvider.platform.android.navBar.alignTitle('center');
                    $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
                    $ionicConfigProvider.platform.android.navBar.transition('view');
                    $ionicConfigProvider.platform.android.views.transition('ios');
                    $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
                    $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
                    $ionicConfigProvider.platform.android.tabs.style('standard');
                    $ionicConfigProvider.platform.android.tabs.position('bottom');
                    $ionicConfigProvider.platform.android.form.toggle('large');

                    $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
                    $ionicConfigProvider.platform.default.backButton.text(false);
                })
                .run(function () {
                    u9.hideLoading();
                })

            .service('debounce', ['$timeout', function ($timeout) {
                return function (func, wait, immediate, invokeApply) {
                    var timeout, args, context, result;
                    function debounce() {
                        /* jshint validthis:true */
                        context = this;
                        args = arguments;
                        var later = function () {
                            timeout = null;
                            if (!immediate) {
                                result = func.apply(context, args);
                            }
                        };
                        var callNow = immediate && !timeout;
                        if (timeout) {
                            $timeout.cancel(timeout);
                        }
                        timeout = $timeout(later, wait, invokeApply);
                        if (callNow) {
                            result = func.apply(context, args);
                        }
                        return result;
                    }
                    debounce.cancel = function () {
                        $timeout.cancel(timeout);
                        timeout = null;
                    };
                    return debounce;
                };
            }])
            .directive('debounce', ['debounce', '$parse', function (debounce, $parse) {
                return {
                    require: 'ngModel',
                    priority: 999,
                    link: function ($scope, $element, $attrs, ngModelController) {
                        var debounceDuration = $parse($attrs.debounce)($scope);
                        var immediate = !!$parse($attrs.immediate)($scope);
                        var debouncedValue, pass;
                        var prevRender = ngModelController.$render.bind(ngModelController);
                        var commitSoon = debounce(function (viewValue) {
                            pass = true;
                            ngModelController.$$lastCommittedViewValue = debouncedValue;
                            ngModelController.$setViewValue(viewValue);
                            pass = false;
                        }, parseInt(debounceDuration, 10), immediate);
                        ngModelController.$render = function () {
                            prevRender();
                            commitSoon.cancel();
                            //we must be first parser for this to work properly,
                            //so we have priority 999 so that we unshift into parsers last
                            debouncedValue = this.$viewValue;
                        };
                        ngModelController.$parsers.unshift(function (value) {
                            if (pass) {
                                debouncedValue = value;
                                return value;
                            } else {
                                commitSoon(ngModelController.$viewValue);
                                return debouncedValue;
                            }
                        });
                    }
                };
            }])

                .factory('Home', function ($q) {
                    var Data = {
                        UserCode: u9.getLoginData().UserCode + '',
                        UserOrgId:u9.getLoginData().OrgId + '',
                        userData:{ userName:"",
                            departmentName:"",
                            departmentId:0,
                            userImage:"" }

                    };

                    //获取网络用户数据(usercode)
                    function getUserData() {
                        var deferred = $q.defer();
                        u9.showLoading();
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IGetUserNameAndDesByCode',
                            params: [],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                Data.userData.userName = data.Name;
                                Data.userData.departmentName = data.Des;
                                //Data.userData.userImage = userdata.Seal;
                                deferred.resolve(Data.userData);
                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        });
                        return deferred.promise;
                    }

                    //获取用户部门信息
                    function getUserDepartment() {
                        var deferred = $q.defer();
                        u9.showLoading();
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IGetDeptInfo',
                            params: [],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                Data.userData.departmentName = data.Name;
                                Data.userData.departmentId = data.ID;
                                deferred.resolve(Data.userData);
                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        });
                        return deferred.promise;
                    }

                    // 在133服务器使用
                    ////获取网络用户数据(usercode)
                    //function getUserData() {
                    //    var deferred = $q.defer();
                    //    u9.showLoading();
                    //    u9.callSV({
                    //        name: 'UFIDA.U9.ISV.MFGRestContactSV.Contact.IGetDepOperaterInfo',
                    //        params: [Data.UserCode],
                    //        onSuccess: function (data) {
                    //            u9.hideLoading();
                    //            var userdata =  data[0];
                    //            Data.userData.userName = userdata.OperaterName;
                    //            Data.userData.departmentName = userdata.Depterment;
                    //            Data.userData.userImage = userdata.Seal;
                    //            deferred.resolve(Data.userData);
                    //        },
                    //        onFailure: function (err) {
                    //            u9.hideLoading();
                    //            console.log(err);
                    //            deferred.reject(err);
                    //        }
                    //    });
                    //    return deferred.promise;
                    //}

                    //获取内存用户数据
                    function getLocalUserData() {
                        return Data.userData;
                    }

                    return {
                        getUserData: getUserData,
                        getLocalUserData:getLocalUserData,
                        getUserDepartment:getUserDepartment
                    }
                })
                .factory('Sign', function ($q) {
                    var time = new Date().getTime();
                    var Data = {
                        //每月签到数据
                        monthData: [{
                            id: 0,
                            position: '用友软件园 用友软件园 用友软件园 用友软件园',
                            time: time
                        }, {
                            id: 1,
                            position: '用友软件园 南门',
                            time: time
                        }, {
                            id: 2,
                            position: '用友软件园 南门',
                            time: time
                        }, {
                            id: 3,
                            position: '用友软件园 南门',
                            time: time
                        }, {
                            id: 4,
                            position: '用友软件园 南门',
                            time: time
                        }, {
                            id: 5,
                            position: '用友软件园 南门',
                            time: time
                        }, {
                            id: 6,
                            position: '用友软件园 南门',
                            time: time
                        }, {
                            id: 7,
                            position: '用友软件园 北门',
                            time: time
                        }],
                        UserCode: u9.getLoginData().UserCode + '',
                        UserOrgId:u9.getLoginData().OrgId + ''
                    };

                    function all() {
                        return Data.monthData;
                    }
                    //提交签到数据(用户编码，时间，组织id，地点，省，市，段1，段2)
                    function submitSignData(time,location,province,city) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        var signData = [{
                            UserCode:Data.UserCode,
                            SignDate:time,
                            OrgID:Number(Data.UserOrgId),
                            SignPlace:location,
                            Provice:province,
                            County:city,
                            Segment1:"",
                            Segment2:""
                        }]
                        var jsonData = {
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.ISignInSV',
                            params: [signData],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                deferred.resolve(data);
                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        };
                        u9.callSVAlone(jsonData);
                        return deferred.promise;
                    }


                    //获取每月签到数据(开始时间，结束时间，人员编码，状态)
                    function getMonthSignData(startTime,endTime) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IQuerySignDataSV',
                            params: [startTime,endTime,Data.UserCode],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                console.log(data);
                                deferred.resolve(data);
                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        });
                        //
                        //deferred.resolve(angular.copy(Data.monthData));
                        return deferred.promise;
                    }

                    function getProvinceCity(location) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        $http({
                            method: 'POST',
                            url: 'http://api.map.baidu.com/geocoder/v2/',
                            params: {
                                'ak': "4fnwY1lCfnnoW3a55aKaMf9g",
                                'callback': "renderReverse",
                                'location': location ,
                                'output': "json",
                                'pois':"0"
                            }
                        }).success(function(data) {
                            console.log(data);
                            deferred.resolve(data);

                        }).error(function(err) {
                            console.log(err);
                            deferred.reject(err);
                        });
                        return deferred.promise;
                    }

                    function getPlaceAround(location) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        $http({
                            method: 'POST',
                            url: 'http://api.map.baidu.com/geocoder/v2/',
                            params: {
                                'ak': "4fnwY1lCfnnoW3a55aKaMf9g",
                                'callback': "renderReverse",
                                'location': location ,
                                'output': "json",
                                'pois':"0"
                            }
                        }).success(function(data) {
                            console.log(data);
                            deferred.resolve(data);

                        }).error(function(err) {
                            console.log(err);
                            deferred.reject(err);
                        });
                        return deferred.promise;
                    }
                    return {
                        all: all,
                        getMonthSignData: getMonthSignData,
                        submitSignData:submitSignData,
                        //获取省市信息
                        getProvinceCity:getProvinceCity,
                        //获取周边地点信息
                        getPlaceAround:getPlaceAround
                    }
                })

                .factory('Report', function ($q) {
                    var Data = {
                        UserCode: u9.getLoginData().UserCode + '',
                        UserOrgId:u9.getLoginData().OrgId + '',
                        projects:[{
                            ID:1,
                            Name:"项目1"
                        },{
                            ID:2,
                            Name:"项目2"
                        },{
                            ID:3,
                            Name:"项目3"
                        }]
                    };

                    function submitReportData(projectId,projectName,deptId,apm,hour,content,time,isFillIn,state) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        var reportData = [{
                            //ID:null,
                            Project:projectId,
                            ProjectName:projectName,
                            Org:Data.UserOrgId,
                            Dept:deptId,
                            TimeSlotEnum:apm,
                            ManHour:hour,
                            WorkContent:content,
                            UserCode:Data.UserCode,
                            OperationDate:time,
                            IsFillIn:isFillIn,
                            StateEnum:state
                        }]
                        var jsonData = {
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.ICreateWorkSV',
                            params: [reportData],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                deferred.resolve(data);
                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        };
                        u9.callSVAlone(jsonData);
                        return deferred.promise;
                    }

                    function updateReportData(reportId,projectId,projectName,deptId,apm,hour,content,time,isFillIn,state) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        var reportData = [{
                            ID:reportId,
                            Project:projectId,
                            ProjectName:projectName,
                            Org:Data.UserOrgId,
                            Dept:deptId,
                            TimeSlotEnum:apm,
                            ManHour:hour,
                            WorkContent:content,
                            UserCode:Data.UserCode,
                            OperationDate:time,
                            IsFillIn:isFillIn,
                            StateEnum:state
                        }]
                        var jsonData = {
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IUpdateWorkSV',
                            params: [reportData],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                deferred.resolve(data);
                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        };
                        u9.callSVAlone(jsonData);
                        return deferred.promise;
                    }

                    //获取每日汇报数据(开始时间，结束时间，人员编码，状态)
                    function getDayReportData(startTime,endTime) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IQueryWorkInfo',
                            params: [startTime,endTime,Data.UserCode,-1],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                console.log(data);
                                deferred.resolve(data);
                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        });
                        return deferred.promise;
                    }

                    //根据简称搜索获取项目列表()
                    function searchProject(search) {
                        var deferred = $q.defer();
                        u9.showLoading();
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IQueryProjectInfo',
                            params: [search],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                console.log(data);
                                deferred.resolve(data);

                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        });
                        return deferred.promise;
                    }

                    //获取历史项目列表()
                    function getHistoryProject() {
                        var deferred = $q.defer();
                        u9.showLoading();
                        u9.callSV({
                            name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IGetHistoryProj',
                            params: [],
                            onSuccess: function (data) {
                                u9.hideLoading();
                                console.log(data);
                                deferred.resolve(data);

                            },
                            onFailure: function (err) {
                                u9.hideLoading();
                                console.log(err);
                                deferred.reject(err);
                            }
                        });
                        return deferred.promise;
                    }
                    return {
                        submitReportData: submitReportData,
                        getDayReportData:getDayReportData,
                        searchProject:searchProject,
                        updateReportData:updateReportData,
                        getHistoryProject:getHistoryProject
                   }
                })

                .filter('filterApm',function(){
                    return function(e){
                        if(e==1) {
                            return "上午";
                        }
                        else if(e==2){
                            return "下午";
                        }
                        else if(e==3){
                            return "全天";
                        }
                        return "上午";
                    }
                })
                .filter('filterDate', function () {
                    return function (e) {
                        return e.substring(0, e.indexOf(" "));
                    }
                })
                .controller('HomeCtrl', function($scope,$state,Home) {
                    $scope.userName = "";
                    $scope.userDepartment = "";
                    $scope.userImage = "";
                    var weekday=new Array(7);
                    weekday[0]="日";
                    weekday[1]="一";
                    weekday[2]="二";
                    weekday[3]="三";
                    weekday[4]="四";
                    weekday[5]="五";
                    weekday[6]="六";
                    var d = new Date();
                    $scope.year = d.getFullYear();
                    $scope.month = d.getMonth()+1;
                    $scope.date = d.getDate();
                    $scope.day = weekday[d.getDay()];
                    $scope.apm = "AM";
                    $scope.time = d.toLocaleTimeString();
                    if($scope.time.indexOf("下午")>=0){
                        $scope.apm = "PM";
                        $scope.time = $scope.time.replace("下午","");
                    }
                    else if($scope.time.indexOf("上午")>=0){
                        $scope.apm = "AM";
                        $scope.time = $scope.time.replace("上午","");
                    }
                    //else if($scope.time.indexOf("PM")>=0){
                    //    alert($scope.time);
                    //    $scope.apm = "PM";
                    //    //$scope.time = $scope.time.substring(0,$scope.time.lastIndexOf(":"));
                    //}
                    //else if($scope.time.indexOf("AM")>=0){
                    //    $scope.apm = "AM";
                    //    //$scope.time = $scope.time.substring(0,$scope.time.lastIndexOf(":"));
                    //}
                    $scope.time = $scope.time.substring(0,$scope.time.lastIndexOf(":"));
                    if($scope.time.indexOf("GMT+8")>=0){
                        $scope.time = $scope.time.replace("GMT+8 ","");
                    }

                    Home.getUserData().then(function (data) {
                        if(data) {
                            $scope.userName = data.userName;
                        }
                        Home.getUserDepartment().then(function (data) {
                            if(data) {
                                $scope.userDepartment = data.departmentName;
                            }
                        });
                    });
                    $scope.sign =  function(){
                        $state.go("sign",{});
                    };

                    $scope.report =  function(){
                        $state.go("report",{});
                    };
                })
                .controller('ReportCtrl', function($scope,Home,$ionicPopup,Report,$ionicModal) {
                    $scope.data = {
                        apm: 0
                    };
                    var radioValue = 0;//时间段
                    var hour = 4;//工时
                    var isFillIn = false;//是否补填
                    var state = 1;//提交状态
                    var isUpdate = false;//判断提交按钮是提交还是更新的标志位
                    var reportId = 0;//日志id(更新日志时需要)
                    var updateApm = 0;//储存更新的日志的apm

                    //$scope.radioChoice = '1';//单选纽的值
                    $scope.task_date = "";//日期
                    $scope.task_detail = "";//报告内容
                    $scope.searchProjectName = "";//查找项目
                    $scope.task_id = 0;//项目id
                    $scope.task_name = "";//项目名称

                    var userData = Home.getLocalUserData();
                    $scope.userName = userData.userName;
                    $scope.userDepartment = userData.departmentName;
                    $scope.userDepartmentId = userData.departmentId;
                    $scope.userImage = userData.userImage;
                    var weekday=new Array(7);
                    weekday[0]="日";
                    weekday[1]="一";
                    weekday[2]="二";
                    weekday[3]="三";
                    weekday[4]="四";
                    weekday[5]="五";
                    weekday[6]="六";
                    var d = new Date();
                    $scope.year = d.getFullYear();
                    $scope.month = d.getMonth()+1;
                    $scope.date = d.getDate();
                    $scope.task_date = $scope.year+"-"+$scope.month+"-"+$scope.date;
                    //提交报告时间
                    var report_time = $scope.task_date+" "+d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
                    var day_start_time = $scope.task_date+" "+"00:00:00";
                    var day_end_time = $scope.task_date+" "+"23:59:59";
                    $scope.day = weekday[d.getDay()];
                    $scope.apm = "AM";
                    $scope.time = d.toLocaleTimeString();
                    if($scope.time.indexOf("下午")>=0){
                        $scope.apm = "PM";
                        $scope.time = $scope.time.replace("下午","");
                    }
                    else if($scope.time.indexOf("上午")>=0){
                        $scope.apm = "AM";
                        $scope.time = $scope.time.replace("上午","");
                    }
                    $scope.time = $scope.time.substring(0,$scope.time.lastIndexOf(":"));
                    if($scope.time.indexOf("GMT+8")>=0){
                        $scope.time = $scope.time.replace("GMT+8 ","");
                    }
                    $scope.radio_list = [
                        { text: "上午", value: 1 },
                        { text: "下午", value: 2 },
                        { text: "全天", value: 3 }
                    ];
                    Report.getDayReportData(day_start_time,day_end_time).then(function (data) {
                        for (var i in data) {
                            var time = data[i].OperationDate;
                            data[i].OperationDate = time.replace(/\//g,"-");
                        }
                        $scope.report_list = data;
                    });
                    //$scope.scrollText = function (){
                    //    window.scrollTo(0,500);
                    //};
                    $scope.clearSearch = function () {
                        $scope.searchProjectName = '';
                    };
                    $scope.filterProject = function (search) {
                        Report.searchProject(search).then(function (data) {
                            $scope.projects = data;
                            if(data.length==0) {
                                u9.alert("数据为空");
                            }
                        });
                    };
                    $scope.changeDate = function(){
                        var options = {
                            date: new Date(),
                            mode: 'date',
                            doneButtonLabel: '确定',
                            cancelButtonLabel: "取消"
                        };
                        u9.plugins.datePicker.show(options, function(date){
                            if(date == 'Invalid Date' || date == 'Nan-Nan'){
                                return;
                            }
                            if(date.getTime()< d.getTime()){
                                isFillIn = true;//补填
                            }
                            $scope.task_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
                            report_time = $scope.task_date+" "+date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                            for(var i in $scope.radio_list){
                                $scope.radio_list[i].check = false;
                            }
                            $scope.$apply();

                            day_start_time = $scope.task_date+" "+"00:00:00";
                            day_end_time = $scope.task_date+" "+"23:59:59";
                            Report.getDayReportData(day_start_time,day_end_time).then(function (data) {
                                for (var i in data) {
                                    var time = data[i].OperationDate;
                                    data[i].OperationDate = time.replace(/\//g,"-");
                                }
                                $scope.report_list = data;
                                d = date;
                            });
                        });
                    }

                    $scope.radioChange = function(item) {
                        radioValue = item.value;
                        if(radioValue==1||radioValue==2){
                            hour = 4;
                        }
                        else if(radioValue==3){
                            hour = 8;
                        }
                        console.log("Selected apm, text:", item.text, "value:", item.value);
                    };
                    // Report.submitReportData(projectId,projectName,deptId,apm,hour,content,time,isFillIn,state)
                    //判断日志是否可以提交，
                    function isSubmit(apmValue){
                        var issubmit = true;
                        if(apmValue==3) {
                            for(var i in $scope.report_list) {
                                var apm = $scope.report_list[i].TimeSlotEnum;
                                //如果有上午或下午或全天的都不能提交
                                if(apm==1||apm==2||apm==3){
                                    issubmit = false;
                                    break;
                                }
                            }
                        }
                        else if(apmValue==2) {
                            for(var i in $scope.report_list) {
                                var apm = $scope.report_list[i].TimeSlotEnum;
                                //如果有下午或全天的都不能提交
                                if(apm==2||apm==3){
                                    issubmit = false;
                                    break;
                                }
                            }
                        }
                        else if(apmValue==1) {
                            for(var i in $scope.report_list) {
                                var apm = $scope.report_list[i].TimeSlotEnum;
                                //如果有上午或全天的都不能提交
                                if(apm==1||apm==3){
                                    issubmit = false;
                                    break;
                                }
                            }
                        }
                        return issubmit;
                    }

                    $scope.submitReportData = function() {

                        //更新
                        if(isUpdate){
                            if(updateApm==radioValue){
                            Report.updateReportData(reportId,$scope.task_id,$scope.task_name,$scope.userDepartmentId,radioValue,hour,$scope.task_detail,report_time,isFillIn,state).then(function (data) {
                                if(data && data.length>0){
                                    u9.alert("更新日志成功");
                                    $scope.data.apm = 0;
                                    $scope.task_detail = "";//报告内容
                                    $scope.task_name = "";//项目名称
                                    isUpdate = false;
                                    Report.getDayReportData(day_start_time,day_end_time).then(function (data) {
                                        for (var i in data) {
                                            var time = data[i].OperationDate;
                                            data[i].OperationDate = time.replace(/\//g,"-");
                                        }
                                        $scope.report_list = data;
                                    });
                                }
                                else{
                                    u9.alert("更新日志失败");
                                }
                            });
                            }
                            else{
                                u9.alert("更新日志冲突，无法更新");
                            }
                        }
                        //提交
                        else{
                            if(isSubmit(radioValue)){
                                report_time = $scope.task_date+" "+d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
                                $scope.task_detail = document.getElementById('taskDetail').value;
                                Report.submitReportData($scope.task_id,$scope.task_name,$scope.userDepartmentId,radioValue,hour,$scope.task_detail,report_time,isFillIn,state).then(function (data) {
                                    if(data && data.length>0){
                                        u9.alert("提交日志成功");
                                        $scope.data.apm = 0;
                                        $scope.task_detail = "";//报告内容
                                        $scope.task_name = "";//项目名称
                                        Report.getDayReportData(day_start_time,day_end_time).then(function (data) {
                                            for (var i in data) {
                                                var time = data[i].OperationDate;
                                                data[i].OperationDate = time.replace(/\//g,"-");
                                            }
                                            $scope.report_list = data;
                                        });
                                    }
                                    else{
                                        u9.alert("提交日志失败");
                                    }
                                });
                            }
                            else{
                                u9.alert("提交日志冲突，无法提交");
                            }

                        }
                    };

                    $scope.changeReport = function(report) {
                        if(report.StateEnum==2) {
                            u9.alert("日志正在审核，不能编辑");
                        }
                        else{
                            if(report.TimeSlotEnum == 1){
                                $scope.data.apm = 1;
                            }
                            else if(report.TimeSlotEnum == 2){
                                $scope.data.apm = 2;
                            }
                            else if(report.TimeSlotEnum == 3){
                                $scope.data.apm = 3;
                            }
                            state = 1;
                            report_time = report.OperationDate;//日期
                            $scope.task_date = report_time.substring(0,report_time.indexOf(" "));
                            $scope.task_detail = report.WorkContent;//报告内容
                            $scope.task_name = report.ProjectName;//项目名称
                            $scope.task_id = report.Project;//项目id
                            isFillIn = report.IsFillIn;
                            isUpdate = true;
                            reportId = report.ID;
                            updateApm = report.TimeSlotEnum
                            radioValue = report.TimeSlotEnum;
                        }
                    };
                    $ionicModal.fromTemplateUrl('templates/projectList.html', {
                        scope: $scope,
                        animation: 'slide-in-right'
                    }).then(function(modal) {
                        $scope.modal = modal;
                    });
                    $scope.getProject = function () {
                        //$scope.searchProject = ""
                        $scope.modal.show().then(function () {
                                Report.getHistoryProject().then(function (data) {
                                    if(data&&data.length>0) {
                                        $scope.projects = data;
                                    }
                                });
                        });
                    };
                    $scope.confirmSelected = function () {
                        $scope.modal.hide();
                    };
                    $scope.cancelSelected = function () {
                        $scope.modal.hide();
                        $scope.task_id = 0
                        $scope.task_name = "";
                    };
                    $scope.getOneProject = function(project){
                        $scope.task_id = project.ID;
                        $scope.task_name = project.Name;
                    };

                })
                //http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-placeapi
                .controller('SignCtrl', function($scope,$http,$ionicActionSheet,Sign,Home,$ionicModal) {
                    //$scope.date = new Date().getTime();
                    var location = ""//当前选择的地点名
                    var province = "";
                    var city = "";
                    var day = "";//每月的自然天
                    $scope.searchPlace = "";
                    $scope.change_year = "";
                    $scope.change_month = "";
                    $scope.sign_list = [];//储存签到数据
                    var userData = Home.getLocalUserData();
                    $scope.userName = userData.userName;
                    $scope.userDepartment = userData.departmentName;
                    $scope.userImage = userData.userImage;
                    var weekday=new Array(7);
                    weekday[0]="日";
                    weekday[1]="一";
                    weekday[2]="二";
                    weekday[3]="三";
                    weekday[4]="四";
                    weekday[5]="五";
                    weekday[6]="六";
                    var d = new Date();
                    $scope.change_year = $scope.year = d.getFullYear();
                    $scope.change_month = $scope.month = d.getMonth()+1;
                    $scope.date = d.getDate();
                    $scope.day = weekday[d.getDay()];
                    $scope.apm = "AM";
                    $scope.time = d.toLocaleTimeString();
                    if($scope.time.indexOf("下午")>=0){
                        $scope.apm = "PM";
                        $scope.time = $scope.time.replace("下午","");
                    }
                    else if($scope.time.indexOf("上午")>=0){
                        $scope.apm = "AM";
                        $scope.time = $scope.time.replace("上午","");
                    }
                    $scope.time = $scope.time.substring(0,$scope.time.lastIndexOf(":"));
                    if($scope.time.indexOf("GMT+8")>=0){
                        $scope.time = $scope.time.replace("GMT+8 ","");
                    }
                    function getDaysInMonth(year,month){
                        month = parseInt(month,10); //parseInt(number,type)这个函数后面如果不跟第2个参数来表示进制的话，默认是10进制。
                        var temp = new Date(year,month,0);
                        return temp.getDate();
                    }
                    day = getDaysInMonth($scope.year,$scope.month);
                    //d.setDate(25);
                    $scope.thisMonth = $scope.year+"-"+$scope.month+"-"+day+" "
                    +"23:59:59";
                    //d.setMonth(d.getMonth()-1,25);
                    $scope.lastMonth = $scope.year+"-"+$scope.month+"-"+"01"+" "
                    +"00:00:00";
                    Sign.getMonthSignData($scope.lastMonth , $scope.thisMonth).then(function (data) {
                        $scope.sign_list = data;
                        $scope.sign_list.sort(function (a, b) {
                            return a.AttendanceOn < b.AttendanceOn ? 1 : -1;
                        })
                    });
                    $scope.clearSearch = function () {
                        $scope.searchPlace = "";
                    };
                    //if (window.cordova && window.cordova.plugins.Keyboard) {
                    // 进行定位

                    //}

                    var onSuccess = function(position) {
                      //alert('Latitude: '          + position.coords.latitude          + '\n' +
                      //'Longitude: '         + position.coords.longitude         + '\n' +
                      //'Altitude: '          + position.coords.altitude          + '\n' +
                      //'Accuracy: '          + position.coords.accuracy          + '\n' +
                      //'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
                      //'Heading: '           + position.coords.heading           + '\n' +
                      //'Speed: '             + position.coords.speed             + '\n' +
                      //'Timestamp: '         + position.timestamp                + '\n');
                        getdata(position.coords.latitude+","+position.coords.longitude);
                    };

                    function onError(error) {
                      alert('code: '    + error.code    + '\n' +
                      'message: ' + error.message + '\n');
                    }

                    //var posOptions = {maximumAge: 30000, timeout: 5000, enableHighAccuracy: false};
                    //$cordovaGeolocation
                    //  .getCurrentPosition(posOptions)
                    //  .then(function (position) {
                    //    alert("position"+position);
                    //    var lat  = position.coords.latitude
                    //    var long = position.coords.longitude
                    //    getdata(lat+","+long);
                    //  }, function(err) {
                    //    alert('code: '    + err.code    + '\n' +
                    //    'message: ' + err.message + '\n');
                    //  });
                    //var options = {
                    //    date: new Date(),
                    //    mode: 'date', // or 'time'
                    //    allowOldDates: true,
                    //    allowFutureDates: true,
                    //    doneButtonLabel: 'DONE',
                    //    doneButtonColor: '#F2F3F4',
                    //    cancelButtonLabel: 'CANCEL',
                    //    cancelButtonColor: '#000000'
                    //};

                    $ionicModal.fromTemplateUrl('templates/placeList.html', {
                        scope: $scope,
                        animation: 'slide-in-right'
                    }).then(function(modal) {
                        $scope.modal = modal;
                    });

                    $scope.confirmPlaceSelected = function () {
                        if(location == '') {
                            u9.alert("请选择签到地点");
                        }
                        else{
                            $scope.modal.hide();
                            var date = new Date();
                            var datetime = date.getTime();
                            var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " "
                                + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                            //alert(time+"---"+location);
                            Sign.submitSignData(time, location, province, city).then(function (data) {
                                if (data && data.length > 0) {
                                    u9.alert("签到成功");
                                    $scope.sign_list.unshift({
                                        AttendanceOn: datetime,
                                        AttendancePlace: location
                                    })
                                }
                                else {
                                    u9.alert("签到失败");
                                }
                            });
                        }
                    };
                    $scope.cancelPlaceSelected = function () {
                        $scope.modal.hide();
                        location = "";
                    };
                    $scope.getOnePlace = function(place){
                        location = place.name;
                    };

                    $scope.changeMonth = function(){
                        var options = {
                            date: new Date(),
                            mode: 'date',
                            doneButtonLabel: '确定',
                            cancelButtonLabel: "取消"
                        };
                        u9.plugins.datePicker.show(options, function(date){
                            if(date == 'Invalid Date' || date == 'Nan-Nan'){
                                return;
                            }
                            $scope.change_year = date.getFullYear();
                            $scope.change_month = date.getMonth()+1;
                            $scope.$apply();

                            day = getDaysInMonth($scope.change_year,$scope.change_month);
                            //d.setDate(25);
                            $scope.thisMonth = $scope.change_year+"-"+$scope.change_month+"-"+day+" "
                            +"23:59:59";
                            //d.setMonth(d.getMonth()-1,25);
                            $scope.lastMonth = $scope.change_year+"-"+$scope.change_month+"-"+"01"+" "
                            +"00:00:00";
                            Sign.getMonthSignData($scope.lastMonth,$scope.thisMonth).then(function (data) {
                                u9.hideLoading();
                                $scope.sign_list = data;
                                $scope.sign_list.sort(function (a, b) {
                                    return a.AttendanceOn < b.AttendanceOn ? 1 : -1;
                                })
                            });
                        });
                    }

                    function successCallback(data) {
                        //alert(data);
                        data.replace("\n","");
                        data.replace(" ","");
                        var lat = data.substring(data.indexOf("latitude")+10,data.indexOf("lontitude"));
                        var lon = data.substring(data.indexOf("lontitude")+11,data.indexOf("radius"));
                        getdata(lat+","+lon);
                    };
                    function failedCallback(error) {
                        alert("error"+error);
                    }
                    //签到（签到时恢复下当前时间）
                    $scope.signIn = function(){
                        u9.showLoading();
                        $scope.change_year = $scope.year;
                        $scope.change_month = $scope.month;
                        //getdata("40.072692,116.240894");
                        if(parent.device.platform == "Android") {
                            parent.baidu_location.getCurrentPosition(successCallback, failedCallback);
                        }
                        else{
                            parent.navigator.geolocation.getCurrentPosition(onSuccess, onError);
                        }
                    }

                    function showlocation(data1,data2){
                            $scope.searchPlace = "";
                            $scope.modal.show().then(function () {
                                $scope.places =  data1.results.concat(data2.results);
                                $scope.$apply();
                            });
                    }

                    //lat<纬度>,lng<经度>  'location': "40.072692,116.240894",
                    function getdata(location){
                        $http({
                            method: 'POST',
                            url: 'http://api.map.baidu.com/geocoder/v2/',
                            params: {
                                'ak': "4fnwY1lCfnnoW3a55aKaMf9g",
                                'callback': "renderReverse",
                                'location': location ,
                                'output': "json",
                                'pois':"0"
                            }
                        }).success(function(data) {
                            //alert(data);
                            var str = data.substring(data.indexOf("("),data.indexOf(")")+1);
                            str = str.replace("(","[");
                            str = str.replace(")","]");
                            var datajson = angular.fromJson(str);
                            var addressComponent = datajson[0].result.addressComponent;
                            province = addressComponent.province;
                            city = addressComponent.city;
                            $http({
                                method: 'POST',
                                url: 'http://api.map.baidu.com/place/v2/search',
                                params: {
                                    'query': "公司",
                                    'location': location,
                                    'radius': 2000,
                                    'output': "json",
                                    'ak': "4fnwY1lCfnnoW3a55aKaMf9g"
                                }
                            }).success(function(data1) {
                                $http({
                                    method: 'POST',
                                    url: 'http://api.map.baidu.com/place/v2/search',
                                    params: {
                                        'query': "小区",
                                        'location': location,
                                        'radius': 2000,
                                        'output': "json",
                                        'ak': "4fnwY1lCfnnoW3a55aKaMf9g"
                                    }
                                }).success(function(data2) {
                                    u9.hideLoading();
                                    showlocation(data1,data2);
                                }).error(function(data) {
                                    alert(data);
                                });

                            }).error(function(data) {
                                alert(data);
                            });
                        }).error(function(err) {
                            alert(err);
                        });
                    }
                })

            angular.element(document).ready(function () {
                angular.bootstrap(document, ['myApp']);
            });
        });
});